﻿using System.Text;

namespace LowCoding.Common
{
    public class GuidHelper
    {
        /// <summary>
        /// 根据GUID获取16位的唯一字符串
        /// </summary>
        /// <param name=\"guid\"></param>
        /// <returns></returns>
        public static string GuidTo16String()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
                i *= ((int)b + 1);
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        /// <summary>
        /// 根据GUID获取19位的唯一数字序列
        /// </summary>
        /// <returns></returns>
        public static long GuidToLongID()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

        /// <summary>
        /// 生成22位唯一的数字 并发可用
        /// </summary>
        /// <returns></returns>
        public static string GenerateUniqueID()
        {
            System.Threading.Thread.Sleep(1); //保证yyyyMMddHHmmssffff唯一
            Random d = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
            string strUnique = DateTime.Now.ToString("yyyyMMddHHmmssffff") + d.Next(1000, 9999);
            return strUnique;
        }

        public static string uuid()
        {
            // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12
            return Guid.NewGuid().ToString();
        }

        public static string uuidN()
        {
            // e0a953c3ee6040eaa9fae2b667060e09
            return Guid.NewGuid().ToString("N");
        }

        public static string uuidD()
        {
            // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12
            return Guid.NewGuid().ToString("D");
        }

        public static string uuidB()
        {
            // {734fd453-a4f8-4c5d-9c98-3fe2d7079760}
            return Guid.NewGuid().ToString("B");
        }

        public static string uuidP()
        {
            // (ade24d16-db0f-40af-8794-1e08e2040df3)
            return Guid.NewGuid().ToString("P");
        }

        public static string uuidX()
        {
            // {0x3fa412e3,0x8356,0x428f,{0xaa,0x34,0xb7,0x40,0xda,0xaf,0x45,0x6f}}
            return Guid.NewGuid().ToString("X");
        }

        /// <summary>
        /// 转成guid
        /// </summary>
        /// <param name="guidString"></param>
        /// <returns></returns>
        public static Guid ToGuid(string guidString)
        {
            //8-4-4-4-12
            ArgumentCheck.NotLength(guidString, nameof(guidString), 32);

            guidString = guidString.ToLower();
            StringBuilder sb = new StringBuilder();
            sb.Append(guidString.Substring(0, 8)).Append('-')
                .Append(guidString.Substring(8, 4)).Append('-')
                .Append(guidString.Substring(12, 4)).Append('-')
                .Append(guidString.Substring(16, 4)).Append('-')
                .Append(guidString.Substring(20));

            return Guid.Parse(sb.ToString());
        }
    }
}